import tkinter as tk
from tkinter import ttk
import os

def populate_tree(tree, node):
    if tree.set(node, "type") != 'directory':
        return

    path = tree.set(node, "fullpath")
    tree.delete(*tree.get_children(node))

    try:
        # 遍历目录下的所有文件和子目录
        for p in os.listdir(path):
            full_path = os.path.join(path, p)
            isdir = os.path.isdir(full_path)
            item_id = tree.insert(node, 'end', text=p, values=[isdir, full_path])
            if isdir:
                tree.insert(item_id, 'end', text='dummy')  # 插入一个占位符，以允许展开
                tree.set(item_id, "type", 'directory')
                tree.set(item_id, "fullpath", full_path)
            else:
                tree.set(item_id, "type", 'file')
                tree.set(item_id, "fullpath", full_path)
    except PermissionError:
        pass  # 忽略权限错误，继续遍历其他项

def update_tree(event):
    selected_item = tree.selection()
    if not selected_item:
        return
    item = selected_item[0]
    if tree.item(item)['values'][0]:  # 如果是目录，则更新其内容
        populate_tree(tree, item)

def on_treedblclick(event):
    item = tree.identify_row(event.y)
    if tree.set(item, "type") == 'directory':
        populate_tree(tree, item)
    else:
        print(f"File selected: {tree.set(item, 'fullpath')}")

root = tk.Tk()
root.title("Directory Browser")

# 创建左侧框架
left_frame = ttk.Frame(root, padding="10")
left_frame.pack(side="left", fill="both", expand=True)

# 创建 Treeview 组件来显示目录结构
tree = ttk.Treeview(left_frame, columns=("type", "fullpath"), show="tree")
tree.heading("#0", text="Directory Structure")
tree.column("#0", width=300)
tree.column("type", width=0, stretch=tk.NO)  # 隐藏 type 列
tree.column("fullpath", width=0, stretch=tk.NO)  # 隐藏 fullpath 列

vsb = ttk.Scrollbar(left_frame, orient="vertical", command=tree.yview)
vsb.pack(side='right', fill='y')
tree.configure(yscrollcommand=vsb.set)

tree.pack(side="left", fill="both", expand=True)

# 初始化根目录
root_directory = os.getcwd()  # 当前工作目录，可以根据需要更改
root_node = tree.insert('', 'end', text=root_directory, values=['directory', root_directory])
tree.set(root_node, "type", 'directory')
tree.set(root_node, "fullpath", root_directory)
populate_tree(tree, root_node)

# 绑定事件
tree.bind('<<TreeviewOpen>>', update_tree)
tree.bind('<Double-1>', on_treedblclick)

# 创建右侧标签
right_label = ttk.Label(root, text="Installation Directory")
right_label.pack(side="right", padx=10)

root.mainloop()